﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSpinBox>
#include <QFileDialog>
#include <QMessageBox>
#include <QProcess>
#include <QJsonObject>
#include <QJsonArray>
#include "ImageLabel.h"
#include "ScreenshotTool.h"
#include "HoverButton.h"
#include "ReportGenerator.h"
#include "MarkableImage.h"
#include "Attribute.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,m_imageLabel(nullptr)
    ,m_screenshotTool(nullptr)
    ,m_hoverButton(nullptr)
    ,m_reportGenerator(new ReportGenerator(this))
    ,m_markableImage(new MarkableImage(this))
    ,m_options(new Attribute(this))
    ,m_picPath(QCoreApplication::applicationDirPath())
{
    ui->setupUi(this);
    setupUI();
    setWindowTitle("图片标记点工具");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::openImage()
{
    QString fileName = QFileDialog::getOpenFileName(
        this,
        "打开图片",
        "",
        "图片文件 (*.png *.jpg *.jpeg *.bmp *.tif)"
        );

    if (!fileName.isEmpty()) {
        m_imageLabel->loadImage(fileName);
        ui->statusBar->showMessage("已加载图片: " + fileName, 3000);
    }
}

void MainWindow::saveImage() {
    if (m_imageLabel->pixmap(Qt::ReturnByValue).isNull()) {
        QMessageBox::warning(this, "警告", "没有图片可保存!");
        return;
    }

    QString filePath = QFileDialog::getSaveFileName(this, "保存图片", "",
                                                    "PNG (*.png);;JPEG (*.jpg *.jpeg);;BMP (*.bmp)");
    if (!filePath.isEmpty()) {
        m_imageLabel->saveImage(filePath);
    }
}

void MainWindow::setupUI(){

    QPushButton *openButton = new QPushButton("打开图片", this);
    connect(openButton, &QPushButton::clicked, this, &MainWindow::openImage);
    connect(this,&MainWindow::sigGenerateReport,m_reportGenerator,&ReportGenerator::generateReport);
    // 连接信号和槽
    connect(m_markableImage, &MarkableImage::pointSelected,this, &MainWindow::onPointSelected);

    ui->verticalLayout_6->addWidget(m_markableImage);

    //设置右侧的图片
    m_markableImage->setBackgroundImage(QCoreApplication::applicationDirPath()+"/矢量智能对象.png");

    ui->toolBar->addWidget(openButton);

    m_imageLabel = new ImageLabel(this);
    ui->scrollArea->setWidget(m_imageLabel);
    ui->scrollArea->setWidgetResizable(true);

    m_hoverButton = new HoverButton;
    ui->verticalLayout_3->addWidget(m_hoverButton);

    ui->verticalLayout_5->addWidget(m_reportGenerator->getTableWidgetPtr());

    ui->scrollArea_3->setWidget(m_options);

    ui->statusBar->showMessage("准备就绪");  
}

void MainWindow::on_screenshot_Btn_clicked(){
    if(m_screenshotTool == nullptr){
        m_screenshotTool = new ScreenshotTool();
        connect(m_screenshotTool,&ScreenshotTool::sigShowMainwindow,this,[this](){
            this->show();
        });
    }
    this->hide();
    m_screenshotTool->takeScreenshot();
}


void MainWindow::on_recognize_Btn_clicked(){
    // 获取当前工作目录
    QString workingDir = QCoreApplication::applicationDirPath();

    // 设置Python脚本路径（假设脚本与应用程序在同一目录）
    QString scriptPath = workingDir + "/image_recognition.py";

    // 创建进程并执行Python脚本
    QProcess process;
    process.start("python", QStringList() << scriptPath << m_picPath);

    if (!process.waitForStarted()) {
        ui->statusBar->showMessage("无法启动Python进程");
        return;
    }

    // 等待进程完成（最多30秒）
    if (!process.waitForFinished(30000)) {
        ui->statusBar->showMessage("处理超时");
        return;
    }

    // 读取输出
    QByteArray output = process.readAllStandardOutput();
    QByteArray error = process.readAllStandardError();

    if (!error.isEmpty()) {
        ui->statusBar->showMessage("错误: " + error);
    } else {
        ui->statusBar->showMessage("识别结果:\n" + output);
    }


    //测试
    QJsonObject dataObj;
    dataObj["quantity"] = 4;
    QJsonArray ary{12.45,65.78};
    dataObj["positions"] = ary;
    QJsonObject obj;
    obj["types"] = 3;
    obj["data"] = dataObj;
    m_reportGenerator->setData(obj);
}


void MainWindow::on_path_Btn_clicked(){
    QString curPath = QCoreApplication::applicationDirPath();
    QString strPath = QFileDialog::getSaveFileName(this,"设置路径",curPath,"File(*)");
    if(strPath != ""){
        m_picPath = strPath;
        qDebug() << m_picPath;
    }
    else{
        QMessageBox::warning(this, "警告", "路径错误!");
    }

}


void MainWindow::on_report_Btn_clicked(){
    //记录测试人员信息
    QStringList info ;
    info << m_options->getValueOption_1()
         << m_options->getValueOption_2()
         << m_options->getValueOption_3()
         << m_options->getValueOption_4()
         << m_options->getValueOption_5();
    m_reportGenerator->setWordInfo(info);

    emit sigGenerateReport();
}

void MainWindow::onPointSelected(const int &index){
    qDebug() << "点" << index + 1 << "被选中";
    m_reportGenerator->setCurPoint(index + 1);//index从0开始的
}
